<?php
/**
 * Created by PhpStorm.
 * Admininfo: Administrator
 * Date: 2018/3/21
 * Time: 15:37
 */
namespace app\admin\model;
use think\Model;
class Goods extends Model{
    protected $resultSetType = 'collection';
    protected $autoWriteTimestamp = true;
    protected $createTime = 'goods_addtime';
    protected $updateTime = 'goods_edittime';
    /**
     * @param $value
     * @return bool|string
     * 处理商铺的经营类别将数组用逗号分隔存库
     */
    protected function setGoodUrlimgAttr($value)
    {
        if($value){
            return trim($value,',');
        }else{
            return false;
        }
    }
    /**
     * @return array|\think\model\relation\BelongsTo
     */
    public  function shop(){
        return $this->belongsTo('Shop','shop_id')->field('id,shop_name,com_avg');
    }
    /**
     * @return array|\think\model\relation\BelongsTo
     */
    public  function goodsclassify(){
        return $this->belongsTo('Goodsclassify','classify_id')->field('id,classify_name,classify_image');
    }

    /**
     * @param $relation
     * @param $page
     * @param string $keywords
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
  public function getlistrelation($relation,$page,$keywords,$order="id desc",$moneytype,$saletype,$classifyid){
          if(!$relation){
              $relation='shop,goodsclassify';
          }
          if($moneytype==1 && $saletype==1){
              $order="goods_price desc,sale_num desc";
          }else if($moneytype==1 && $saletype==2){
              $order="goods_price desc,sale_num asc";
          }else if($moneytype==2 && $saletype==2){
              $order="goods_price asc,sale_num asc";
          }else if($moneytype==2 && $saletype==1){
              $order="goods_price asc,sale_num desc";
          }
          if($moneytype==1){
              $order=" goods_price desc";
          }else if($moneytype==2){
              $order=" goods_price asc";
          }
          if($saletype==1){
              $order="sale_num desc";
          }elseif ($saletype==2){
              $order="sale_num asc";
          }
        if($keywords){
            $where['goods_name|b.classify_name']=['like','%'.$keywords.'%'];
        }
        //商品分类id搜查
        if($classifyid){
            $where['classify_id']=$classifyid;
        }
        $where['goods_status']=1;
        $page=$page?$page:1;
        $list=collection(
               self::with($relation)
                ->where($where)
                ->join('ec_goodsclassify b','ec_goods.classify_id=b.id',left)
                ->page($page,15)
                ->field('ec_goods.*')
                ->order($order)
                ->select()
              )->toArray();
      foreach ($list as $k=>$v){
            $list[$k]['good_urlimg']=explode(',',$v['good_urlimg']);
        }
        return $list;
    }
}